﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Twi.COMMON.Core;
using System.Data;
using System.Data.Common;
using Twi.DataAccess.Common;

namespace Twi.Modules.BIM
{
    public class _Authority : ModuleBase
    {
        public static readonly _Authority Instance = new _Authority();


        /// <summary>
        /// 用户登录验证
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="pwd">密码</param>
        /// <param name="msg">返回信息</param>
        /// <returns>当前登入用户信息</returns>
        public TwiUserInfo VerifyUserLogin(string userName, string pwd)
        {
            UserContext.VerifyUserLogin(userName, pwd);
            Dictionary<string, object> dict = new Dictionary<string, object>();
            dict.Add("FNAME", userName);
            dict.Add("FPWD", pwd);
            DataTable dt = ModuleHelper.Instance.GetBySimpleCondition("TUSER", dict, null);
            if (dt.Rows.Count == 0)
            {
                throw new Exception("用户名或密码错误");
            }
            else
            {
                if (!(dt.Rows[0]["FISACTIVE"] + "").Equals("1"))
                {
                    throw new Exception("用户已锁定，请联系管理员进行解锁");
                }
                else
                {
                    DataRow dr = dt.Rows[0];
                    TwiUserInfo userInfo = new TwiUserInfo
                    {
                        FID = dr["FID"].ToString(),
                        FNAME = dr["FNAME"].ToString(),
                        FPWD = dr["FPWD"].ToString(),
                        FREALNAME = dr["FREALNAME"].ToString(),
                        FSEX = dr["FSEX"].ToString(),
                        FDEPARTMENTID = dr["FDEPARTMENTID"].ToString(),
                        FDUTYID = dr["FDUTYID"].ToString(),
                        FDEPARTMENTTCODE = dr["FDEPARTMENTTCODE"].ToString(),
                        FDUTYNAME = dr["FDUTYNAME"].ToString()
                    };
                    return userInfo;
                }
            }
        }

        public string EditPwd(string userid, string TableName, string oldpwd, string newpwd)
        {
            string resrult = "";
            string strSql = string.Format("select count(*) from tuser where fid={0}FID and fpwd={0}FPWD ", ParameterPrefix);
            List<DbParameter> paras = new List<DbParameter>();
            paras.Add(DB.CreateDbParameter("FID", userid));
            paras.Add(DB.CreateDbParameter("FPWD", oldpwd));
            DataTable dt = DB.ExecuteDataTable(strSql, paras);
            if (int.Parse(dt.Rows[0][0].ToString()) > 0)
            {
                string strSql1 = string.Format("update tuser set fpwd={0}FPWD where fid={0}FID  ", ParameterPrefix);
                List<DbParameter> paras1 = new List<DbParameter>();

                paras1.Add(DB.CreateDbParameter("FPWD", newpwd));
                paras1.Add(DB.CreateDbParameter("FID", userid));
                int resultEdit = DB.ExecuteNonQuery(strSql1, paras1);
                if (resultEdit > 0)
                {
                    resrult = "密码修改成功，请重新登陆！";
                }
                else
                {
                    resrult = "密码修改错误，请重新输入！";
                }
                // DataTable dt1 = DB.ExecuteDataTable(strSql1, paras1);

            }
            else
            {
                resrult = "原始密码错误，请重新输入！";

            }
            return resrult;

        }


        /// <summary>
        /// 获取功能模块树
        /// </summary>
        /// <returns></returns>
        public List<TreeNodeStruct> GetModuleTreeData()
        {
            DataTable dt = ModuleHelper.Instance.GetAll("BIM_MODULE");
            TreeNodeMapping mapping = new TreeNodeMapping();
            mapping.IDField = "FNAME";
            mapping.ParentIDField = "FPARENTNAME";
            mapping.TextField = "FTEXT";
            mapping.ValueField = "FNAME";
            return TwiTreeHelper<TreeNodeStruct>.GetTreeData(dt, mapping);
        }

        /// <summary>
        /// 获取指定角色拥有的操作权限
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        public DataTable GetOperationListByRoleID(string roleID)
        {
            string strSql = string.Format("select * from BIM_RoleInOperation where FRoleID={0}FRoleID", ParameterPrefix);
            List<DbParameter> paras = new List<DbParameter>();
            paras.Add(DB.CreateDbParameter("FRoleID", roleID));
            return DB.ExecuteDataTable(strSql, paras);
        }


        /// <summary>
        /// 根据功能模块获取对应操作
        /// </summary>
        /// <param name="moduleName"></param>
        /// <returns></returns>
        public DataTable GetOperationListByModuleName(string moduleName)
        {
            string strSql = string.Format("select O.*,M.FText as ModuleText from BIM_Operation O left join BIM_Module M on O.FModuleName = M.FName where FModuleName={0}FModuleName", ParameterPrefix);
            List<DbParameter> paras = new List<DbParameter>();
            paras.Add(DB.CreateDbParameter("FModuleName", moduleName));
            return DB.ExecuteDataTable(strSql, paras);
        }


        /// <summary>
        /// 获取操作列表
        /// </summary>
        /// <param name="moduleName">功能模块名称</param>
        /// <param name="roleId">角色ID</param>
        /// <returns></returns>
        public DataTable GetOperationList(string moduleName, string roleID)
        {
            DataTable dt = GetOperationListByModuleName(moduleName);
            DataTable authorityList = GetOperationListByRoleID(roleID);
            dt.Columns.Add("InAuthority", typeof(int));
            foreach (DataRow dr in dt.Rows)
            {
                int inAuthority = 0;
                foreach (DataRow opreation in authorityList.Rows)
                {
                    if (opreation["FOperationID"].ToString().ToLower() == dr["FID"].ToString().ToLower())
                    {
                        inAuthority = 1;
                        break;
                    }
                }
                dr["InAuthority"] = inAuthority;
            }
            return dt;
        }


        /// <summary>
        /// 设置权限
        /// </summary>
        /// <param name="roleID"></param>
        /// <param name="operationID"></param>
        public void SetRight(string roleID, string[] operationIDs)
        {
            List<TransMultiPara> listTmp = new List<TransMultiPara>();
            int tmpID = 0;
            foreach (string operationID in operationIDs)
            {
                string strSql = string.Format("insert into BIM_RoleInOperation(FID,FRoleID,FOperationID) values('{0}',{1}FRoleID,{1}FOperationID)", Guid.NewGuid() + "", ParameterPrefix);
                List<DbParameter> paras = new List<DbParameter>();
                paras.Add(DB.CreateDbParameter("FRoleID", roleID));
                paras.Add(DB.CreateDbParameter("FOperationID", operationID));
                TransMultiPara tmp = new TransMultiPara();
                tmp.ID = ++tmpID;
                tmp.cmdParams = paras;
                tmp.cmdText = strSql;
                listTmp.Add(tmp);
            }
            DB.ExecuteSqlTransMultiPara(listTmp);
        }

        /// <summary>
        /// 取消权限
        /// </summary>
        /// <param name="roleID"></param>
        /// <param name="operationID"></param>
        public void CancelRight(string roleID, string[] operationIDs)
        {
            List<TransMultiPara> listTmp = new List<TransMultiPara>();
            int tmpID = 0;
            foreach (string operationID in operationIDs)
            {
                string strSql = string.Format("delete from BIM_RoleInOperation where FRoleID={0}FRoleID and FOperationID={0}FOperationID", ParameterPrefix);
                List<DbParameter> paras = new List<DbParameter>();
                paras.Add(DB.CreateDbParameter("FRoleID", roleID));
                paras.Add(DB.CreateDbParameter("FOperationID", operationID));
                TransMultiPara tmp = new TransMultiPara();
                tmp.ID = ++tmpID;
                tmp.cmdParams = paras;
                tmp.cmdText = strSql;
                listTmp.Add(tmp);
            }
            DB.ExecuteSqlTransMultiPara(listTmp);
        }

        /// <summary>
        /// 获取指定用户的功能权限
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public List<string> GetAuthorityListByUserID(string userID)
        {
            //SQL 连接字符串是用+ 而oracle 是用 ||
            string strSql = string.Format(@" select FModuleName||'.'||FName as Authority from BIM_Operation 
                     where FID in (select FOperationID from BIM_RoleInOperation 
                     where FRoleID in(select FRoleID from BIM_UserInRole where FUserID='{0}'))", userID);
            DataTable dt = DB.ExecuteDataTable(strSql);
            List<string> authorityList = new List<string>();
            foreach (DataRow row in dt.Rows)
            {
                authorityList.Add(row[0].ToString());
            }
            return authorityList;
        }

        /// <summary>
        /// 获取指定用户的功能菜单列表
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public List<string> GetMenuInfoListByUserID(string userID)
        {
            string strSql = string.Format(@"select B.FMenuInfo from (                    
 select distinct FModuleName from BIM_Operation 
 where FID in (select FOperationID from BIM_RoleInOperation 
 where FRoleID in(select FRoleID from BIM_UserInRole where FUserID='{0}'))
 )A join BIM_ModuleInfo B on A.FModuleName = B.FModuleName                
 order by B.FSort", userID);
            DataTable dt = DB.ExecuteDataTable(strSql);
            List<string> authorityList = new List<string>();
            foreach (DataRow row in dt.Rows)
            {
                authorityList.Add(row[0].ToString());
            }
            return authorityList;
        }

        /// <summary>
        /// 获取指定用户的功能菜单树
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        public List<TreeNodeStruct> GetMenuTreeByUserID(string userID)
        {
            string strSql = string.Format(@" with myAuthority as(
 select distinct FModuleName,FProjectAbbreviation from BIM_Operation 
 where FID in (select FOperationID from BIM_RoleInOperation 
 where FRoleID in(select FRoleID from BIM_UserInRole where FUserID='{0}'))
 )
 select B.* from myAuthority A join View_BIM_MenuTree B on A.FModuleName=B.FModuleName
 union 
 select B.* from myAuthority A join View_BIM_MenuTree B on A.FProjectAbbreviation=B.FModuleName", userID);
            DataTable dt = DB.ExecuteDataTable(strSql);
            TreeNodeMapping mapping = new TreeNodeMapping();
            mapping.IDField = "FMODULENAME";
            mapping.TextField = "FMODULETEXT";
            mapping.ValueField = "FSRC";
            mapping.ParentIDField = "FPROJECTABBREVIATION";
            return TwiTreeHelper<TreeNodeStruct>.GetTreeData(dt, mapping);
        }

        public System.Xml.Linq.XElement TicketAdd(System.Xml.Linq.XElement xeData)
        {
            Action<System.Xml.Linq.XElement, TwiCommand> processDelegate = (System.Xml.Linq.XElement xe, TwiCommand cmd) =>
            {
                //cmd.ExecuteInsert(xeData);
            };
            return ModuleHelper.Instance.Process(processDelegate);
        }
    }
}
